<template>
  <div class="page-detail">
    <div class="page-title">{{ $t('all.autotext266') }}</div>
    <section class="section">
      <div class="divider-title">
        <a-divider type="vertical" class="divider"/>
        <div>{{ paymentDetails.applyNo }}</div>
        <div class="bg-shape" :class="dynamicClass()">{{ paymentDetails.status | enumValueByKey($const.EXAMINE_TYPE) }}</div>
      </div>
      <a-descriptions bordered size="small">
        <a-descriptions-item :label="$t('all.autotext992')"> {{ paymentDetails.projectNo }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext949')">
          {{ paymentDetails.researchCenterNo + ' - ' + paymentDetails.orgName }}
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext229')"> {{ paymentDetails.type | enumValueByKey($const.SUBJECTANDREESA) }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext1157')">
          {{ paymentDetails.type == this.$const.SUBJECTANDREESA.DAISHENGPI.value ? paymentDetails.researchDetailName : paymentDetails.bankAccount }}
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext867')"> {{ $t('money.unit') }}{{ paymentDetails.totalAmount }} </a-descriptions-item>
      </a-descriptions>
    </section>
    <!-- 审批资料上传 -->
    <section class="section" v-if="paymentDetails.status === 20">
      <div class="divider-title" style="margin:0;">
        <a-divider type="vertical" class="divider"/>
        <div>{{ $t('all.autotext1689') }}</div>
      </div>
      <UploadFileTable
        ref="uploadRef"
        :formList="originDetail.detailList"
        title="custom"
        @uploadFile="uploadFile"
      />
    </section>
    <!-- 审批资料 -->
    <section class="section" v-else>
      <div class="divider-title">
        <a-divider type="vertical" class="divider"/>
        <div>{{ $t('all.autotext1103') }}</div>
      </div>
      <a-table
        ref="table"
        size="default"
        bordered
        :row-key="record => record.id"
        :pagination="false"
        :data-source="paymentDetails.fileArray ? JSON.parse(paymentDetails.fileArray) : []"
      >
        <a-table-column :title="$t('all.autotext334')" data-index="order" width="80px">
          <template slot-scope="text, row, index">{{ index + 1 }}</template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext1706')" data-index="fileType" width="100px">
          <template slot-scope="text,record">{{ record.fileType === 1 ? $t('all.autotext1700') : $t('all.autotext1701') }}</template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext215')" data-index="originalFile" v-if="hasRole">
          <template slot-scope="text,record"><a @click="clickViewFile(record.fileUrl)">{{ record.fileName }}</a></template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext582')" data-index="afterFile">
          <template slot-scope="text,record">
            <div class="afterfile">
              <template v-if="desensePassed(record)">
                <a class="filename" @click="clickViewFile(record.afterFileUrl)">{{ record.fileName }}</a>
                <!-- <a @click="editFile(record, index)">{{ $t('all.autotext1231') }}</a> -->
              </template>
              <template v-else>
                <span class="grey">-</span>
                <!-- <a @click="editFile(record, index, 2)">{{ $t('all.autotext236') }}</a> -->
              </template>
            </div>
          </template>
        </a-table-column>
      </a-table>
    </section>
    <!-- 费用明细 -->
    <section class="section">
      <div class="divider-title">
        <a-divider type="vertical" class="divider"/>
        <div>{{ $t('all.autotext12') }}</div>
      </div>
      <a-descriptions style="margin-top: 20px"></a-descriptions>
      <a-table
        ref="table"
        size="default"
        bordered
        :row-key="record => record.id"
        :pagination="false"
        :data-source="originDetail.detailList"
      >
        <a-table-column :title="$t('all.autotext334')" key="id" data-index="id">
          <template slot-scope="text, row, index">{{ index + 1 }}</template>
        </a-table-column>
        <a-table-column
          :title="$t('all.autotext802')"
          key="applyType"
          data-index="applyType"
          width="260px"
        />
        <a-table-column :title="$t('all.autotext1256')" key="amount">
          <template slot-scope="text, record">
            <span>{{ $t('money.unit') }}{{ record.amount }}</span>
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext1258')" key="fileList">
          <template slot-scope="text, record">
            <div class="btnWrapper">
              <!-- <div><a v-if="paymentDetails.status === 20" @click="addFiles(record)" class="a-class">{{ $t('all.autotext100') }}</a></div> -->
              <a-select
                v-if="paymentDetails.status === 20 && record.supply"
                v-model="record.files"
                mode="multiple"
                :maxTagCount="1"
                style="width: 100%; max-width: 300px;"
                @change="fileChange($event, record, index)"
              >
                <a-select-option v-for="(item, i) in fileList" :key="i" :value="item.fileUrl">
                  {{ item.fileName }}
                </a-select-option>
              </a-select>
              <div>
                <ViewFile
                  v-if="getFileList(record).length > 0 && paymentDetails.status !== 20"
                  :data="getFileList(record)"
                  style="margin-left: 10px"
                >
                  <a class="a-class">{{ $t('all.autotext1421') }}</a>
                </ViewFile>
                <span style="margin-left: 10px" v-else></span>
              </div>
            </div>
          </template>
        </a-table-column>
        <!-- <a-table-column title="操作" v-if="canAudit">
          <template slot-scope="record">
            <a @click="specialCheck(record)" v-if="isSiteCrc && showSpecialCheck(record)">审批</a>
          </template>
        </a-table-column> -->
      </a-table>
    </section>
    <section class="section">
      <div class="divider-title">
        <a-divider type="vertical" class="divider"/>
        <div>{{ $t('all.autotext473') }}</div>
      </div>
      <a-descriptions bordered size="small">
        <a-descriptions-item :label="$t('all.autotext1189')"> {{ paymentDetails.bankAccount }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext551')"> {{ paymentDetails.bankNo }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext497')"> {{ paymentDetails.bankName }} </a-descriptions-item>
      </a-descriptions>
    </section>

    <section
      class="section"
      v-if="paymentDetails.status === 50 || paymentDetails.status === 51 || paymentDetails.status === 60"
    >
      <div class="divider-title">
        <a-divider type="vertical" class="divider"/>
        <div>{{ $t('all.autotext695') }}</div>
      </div>
      <a-descriptions bordered size="small">
        <a-descriptions-item :label="$t('all.autotext1311')"> {{ personalTaxObj.personalTax }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext856')"> {{ personalTaxObj.taxDate | moment() }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext983')"> {{ personalTaxObj.taxRemark }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext512')"><img class="qr-code" src="../../image/qrcode.png" alt=""> <a class="qrcode-a" @click="clickViewFile(personalTaxObj.taxPic)">{{ $t('all.autotext475.1') }}</a> </a-descriptions-item>
      </a-descriptions>
    </section>

    <section class="section" v-if="paymentDetails.status === 60">
      <div class="divider-title">
        <a-divider type="vertical" class="divider"/>
        <div>{{ $t('all.autotext349') }}</div>
      </div>
      <a-descriptions bordered size="small">
        <a-descriptions-item :label="$t('all.autotext1311')"> {{ paymentObj.totalAmount }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext722')"> {{ paymentObj.paymentTime | moment() }} </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext349')"><img class="qr-code" src="../../image/qrcode.png" alt=""> <a class="qrcode-a" @click="clickViewFile(paymentObj.taxPic)">{{ $t('all.autotext475.1') }}</a> </a-descriptions-item>
      </a-descriptions>
    </section>

    <div style="display: flex;flex: 1;height: 100%"></div>
    <section class="btn-wrapper">
      <div>
        <a-button
          type="primary"
          class="btn"
          :disabled="storeAndSubmitButtonState"
          @click="submitData"
          v-if="paymentDetails.status === 20"
        >
          {{ $t('all.autotext218') }}
        </a-button>
        <a-button class="btn" :disabled="storeAndSubmitButtonState" @click="() => this.$router.go(-1)">{{ $t('all.autotext76') }}</a-button>
      </div>
    </section>
    <UploadFile
      :uploadFileVisible="uploadFileVisible"
      :currentTarget="currentTarget"
      @closeUpload="closeUpload"
      ref="UploadFileRef"
    />
    <reModal ref="reModal" />
    <!-- 图片预览 -->
    <a-modal
      width="640px"
      :visible="imgVisible"
      :footer="null"
      @cancel="imgVisible = false"
    >
      <div class="image">
        <img :src="itemFileUrl | dealImageUrl">
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getRecordDetail, updateForUploadAttachment } from '@/api/entrance/record'
// import UploadFile from '../UploadFile'
import UploadFile from '@views/cost-apply/UploadFile.vue'
import ViewFile from '../ViewFile'
import UploadFileTable from '@views/cost-apply/UploadFileTable'
import reModal from '@views/cost-apply/components/reModal'

export default {
  name: 'record-detail-index',
  components: { UploadFile, ViewFile, UploadFileTable, reModal },
  data () {
    return {
      paymentDetails: {},
      status: '',
      originDetail: {},
      uploadFileVisible: false,
      currentTarget: {},
      personalTaxObj: {},
      paymentObj: {},
      imgVisible: false,
      itemFileUrl: '',
      fileList: [],
      storeAndSubmitButtonState: false
    }
  },
  computed: {
    hasRole () {
      if (this.paymentDetails.type === 2) {
        return ['SYS_FINANCE', 'CRC', 'Investigator'].includes(this.$store.getters.roles[0].code)
      } else {
        return ['SYS_FINANCE', 'CRA', 'PM', 'Investigator'].includes(this.$store.getters.roles[0].code)
      }
    }
  },
  provide () {
    return {
      getStoreAndSubmitButtonState: this.getStoreAndSubmitButtonState
    }
  },
  mounted () {
    this.fetchRecordDetail()
  },
  methods: {
    // 脱敏通过
    desensePassed ({ fileUrl, afterFileUrl }) {
      return afterFileUrl && afterFileUrl !== fileUrl
    },
    getFileList (record) {
      const { fileList, fileArr } = record
      if (!fileArr) {
        return fileList
      }
      const fileArrList = JSON.parse(fileArr)
      return fileArrList.map(item => {
        return {
          fileName: item.fileName,
          fileUrl: item.afterUrl || item.originalUrl
        }
      })
    },
    // 文件预览
    clickViewFile (fileUrl) {
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      if (formatImg.test(fileUrl)) {
        this.itemFileUrl = fileUrl
        this.imgVisible = true
      } else {
        // 打开空白页 展示文件
        const fullFileUrl = this.$options.filters.dealImageUrl(fileUrl)
        window.open(fullFileUrl, '_blank')
      }
    },
    /**
     * 获取脱敏后的文件地址
     * @param item 文件对象
     * @return {*|string}
     */
    // getDesensitizedFileUrl (fileList) {
    //   if (!fileList || !fileList.length) return ''
    //   if (fileList.length === 1) return (fileList[0].afterFileUrl || fileList[0].fileUrl)
    //   return fileList?.reduce((pre, cur) => {
    //     return pre ? pre + ',' + (cur.afterFileUrl || cur.fileUrl) : (cur.afterFileUrl || cur.fileUrl)
    //   }, '')
    // },
    getFileArr (item) {
      if (!Array.isArray(item)) return []
      return item.map(e => ({
        afterUrl: e.afterFileUrl || '',
        originalUrl: e.fileUrl || '',
        fileName: e.fileName,
        type: this.$const.UPLOAD_FILE_TYPE.FEE_DETAIL.value
      }))
    },
    async submitData () {
      const errIndex = this.fileList.findIndex(item => [0, 2, 4, 6].includes(item.fileStatus))
      const reUploadIndex = this.fileList.findIndex(item => [1].includes(item.fileType))
      if (errIndex > -1) {
        this.$message.error(this.$t('all.autotext1819'))
        return
      }
      if (reUploadIndex > -1) {
        this.$message.error(this.$t('all.autotext1820'))
        return
      }
      
      let list = this.originDetail.detailList
      let jsonList = []
      list.forEach(({ fileUrl, supply, id, fileList }) => {
        jsonList.push({
          id,
          supply,
          // fileUrl: this.getDesensitizedFileUrl(fileList) || fileUrl
          fileUrl: fileUrl,
          fileArr: this.getFileArr(fileList)
        })
      })

      let fileHash = []
      this.fileList.forEach(e => {
        if (e.fileHash) fileHash.push(e.fileHash)
      })

      let fileArray = this.paymentDetails.fileArray
      if (fileArray) {
        let arr = JSON.parse(this.paymentDetails.fileArray)
        fileHash.forEach((v, i) => {
          if (arr.some(e => e.fileHash === v)) {
            fileHash.splice(i, 1)
          }
        })
      }

      let params = {
        id: this.$route.query.id,
        fileArray: JSON.stringify(this.fileList),
        fileHash: fileHash.join(','),
        clientCostJson: JSON.stringify(jsonList)
      }
      const res = await updateForUploadAttachment(params)
      if (res && res.duplicateCheck) {
        this.$refs.reModal.open(res)
        return
      }
      this.$message.success(this.$t('all.autotext1401'))
      this.$router.go(-1)
    },
    addFiles (record) {
      this.uploadFileVisible = true
      const fileList = record.fileArr ? JSON.parse(record.fileArr)?.map(e => ({ fileName: e.fileName, fileUrl: e.originalUrl, afterFileUrl: e.afterUrl })) : record.fileList
      const formatRecordFileList = fileList.filter(e => e.fileUrl && e.fileUrl.length > 5)
      const formatRecord = Object.assign({}, record, { fileList: formatRecordFileList })
      this.currentTarget = formatRecord
      this.$refs.uploadFileRef.copyData(formatRecord)
      this.$refs.uploadFileRef.resetData()
    },
    // 关闭文件上传
    closeUpload (info) {
      const target = this.originDetail.detailList.find(item => item.id === info.id)
      if (target) {
        target.fileList = info.fileList
        if (target.fileList.length) {
          target.fileUrl = target.fileList.map(item => item.fileUrl).toString()
        } else {
          target.fileUrl = ''
        }
      }
      this.uploadFileVisible = false
      this.$forceUpdate()
    },
    dynamicClass () {
      const status = this.paymentDetails.status

      let className = ''
      switch (status) {
        case 10:
          className = 'orange-shape' // 待提交 TODO UI颜色未指定
          break
        case 20:
          className = 'orange-shape' // 待补充
          break
        case 30:
          className = 'pink-shape' // 审核中
          break
        case 31:
          className = 'pink-shape' // 审核中
          break
        case -1:
          className = 'pink-shape' // 审核驳回
          break
        case 41:
          className = 'orange-shape' // 待完税 TODO UI颜色未指定
          break
        case 50:
          className = 'green-shape' // 待支付
          break
        case 51:
          className = 'green-shape' // 支付中
          break
        case 60:
          className = 'blue-shape' // 已完成
          break
        default:
          className = 'orange-shape'
          break
      }
      return className
    },
    fetchRecordDetail () {
      const datailsId = this.$route.query.id
      getRecordDetail({ id: Number.parseFloat(datailsId) }).then((res) => {
        let status = res.feeApplyDto.status
        this.status = status
        this.paymentDetails = res.feeApplyDto
        this.$nextTick(() => {
          this.originDetail = res
          if (res.feeApplyDto.fileArray) {
            this.fileList = JSON.parse(res.feeApplyDto.fileArray)
            this.fileList = this.fileList.map((item) => ({
              ...item,
              feeApplyDtoStatus: res.feeApplyDto.status
            }))
            this.$refs.uploadRef.backFileList(this.fileList)
          }
        })
        res.detailList.forEach(e => {
          if (e.fileArr) {
            e.files = e.fileList.map(v => v.fileUrl)
          }
        })
        if (status === 50 || status === 51) {
          let taxProcessList = res.processList.filter((item) => {
            return item.proFlowNodeCode === '5020000' // 过滤出个税申报节点，用于渲染
          })[0]
          this.personalTaxObj = {
            personalTax: res.feeApplyDto.personalTax,
            taxRemark: res.feeApplyDto.taxRemark,
            taxDate: taxProcessList.processTime,
            taxPic: taxProcessList.proofUrl
          }
        }
        if (status === 60) {
          let paymentProcessList = res.processList.filter((item) => {
            return item.proFlowNodeCode === '5030000' // 过滤出支付完成节点，用于渲染
          })[0]
          this.paymentObj = {
            totalAmount: res.feeApplyDto.totalAmount,
            paymentTime: paymentProcessList.processTime,
            taxPic: paymentProcessList.proofUrl
          }
        }
      })
    },
    fileChange (event, record, index) {
      const arr = []
      event.forEach(item => {
        let file = this.fileList.filter(e => e.fileUrl === item)[0]
        arr.push(file)
      })
      record.fileList = arr
      record.fileUrl = event.join(',')
    },
    uploadFile (file) {
      this.fileList = file
    },
    getStoreAndSubmitButtonState (loading = false) {
      this.storeAndSubmitButtonState = loading
    }
  }
}
</script>

<style scoped lang="less">
  .ant-descriptions-bordered .ant-descriptions-item-label {
    background: rgba(241, 245, 248, 0.6) !important;
  }
  .orange-shape {
    background: #FFF9DC;
    color: #E88F1A;
  }
  .pink-shape {
    background: #FFEEE9;
    color: #E95A34;
  }
  .green-shape {
    background: #2BDDA8;
    color: #fff;
  }
  .blue-shape {
    background: #0079FF;
    color: #fff;
  }
  .dark-shape {
    background: #0F121B;
    color: #fff;
  }
  .page-detail {
    min-height: calc(100vh - 274px);
    overflow: auto;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 32px 25px 12px 20px;

    .page-title {
      font-size: 18px;
      font-weight: bold;
      color: #232323;
      margin-bottom: 24px;
    }

    .section {
      margin-bottom: 32px;

      .divider-title {
        display: flex;
        flex-direction: row;
        font-size: 16px;
        font-weight: 400;
        color: #0F121B;
        align-items: center;
        margin-bottom: 24px;

        .divider {
          height: 20px;
          width: 4px;
          background: var(--var-primary-color);
          margin-left: 0px;
        }

        .bg-shape {
          width: 64px;
          height: 26px;
          //background: #2BDDA8;
          display: flex;
          justify-content: center;
          align-items: center;
          border-top-left-radius: 13px;
          border-top-right-radius: 13px;
          border-bottom-right-radius: 13px;
          margin-left: 24px;

          font-size: 13px;
          font-weight: 400;
          //color: #fff;
          line-height: 18px;
        }
      }

      .a-class {
        color: #0079FF;
        font-size: 14px;
        line-height: 22px;
      }

      .btnWrapper {
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }

      .qr-code {
        width: 21px;
        height: 21px;
        margin-right: 18px;
      }
      .qrcode-a {
        font-size: 12px;
        color: #0079FF;
        line-height: 16px;
      }
    }

    .btn-wrapper {
      margin-top: 270px;
      display: flex;
      flex:1;
      align-items: flex-end;
      .btn {
        width: 120px;
        height: 36px;
        margin-right: 24px;
      }
    }
  }
  .image {
    img {
      display: block;
      width: 100%;
      margin: 10px auto;
    }
  }
</style>
